package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.RequestUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.listener.easyexcel.SysEmailListener;
import com.settlement.system.model.entity.SysEmail;
import com.settlement.system.model.form.SysEmailForm;
import com.settlement.system.model.query.SysEmailQuery;
import com.settlement.system.model.vo.RegisterEmailVo;
import com.settlement.system.model.vo.SysEmailImportVo;
import com.settlement.system.service.SysEmailService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 邮箱表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-07-17
 */
@RestController
@RequestMapping("/api/v1/email")
@RequiredArgsConstructor
public class SysEmailController {

    @Value("${system.config.secret}")
    private String secret;

    @Value("${system.config.appId}")
    private String appId;

    private final SysEmailService sysEmailService;

    @Operation(summary = "邮箱表分页", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysEmail> getPage(@ParameterObject SysEmailQuery queryParams) {
        Page<SysEmail> result = sysEmailService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存邮箱表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:email:save')")
    public Result<?> saveSysEmail(@RequestBody @Valid SysEmailForm sysEmailForm) {
        boolean result = sysEmailService.saveSysEmail(sysEmailForm);
        return Result.judge(result);
    }

    @Operation(summary = "获取邮箱表信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<SysEmailForm> getSysEmailFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        SysEmailForm sysEmail = sysEmailService.getSysEmailFormData(id);
        return Result.success(sysEmail);
    }

    @Operation(summary = "删除邮箱表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:email:delete')")
    public Result<?> deleteSysEmail(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysEmailService.deleteSysEmail(ids);
        return Result.judge(result);
    }

    @Operation(summary = "注册邮箱表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/register/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:email:register')")
    public Result<?> register(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        sysEmailService.register(ids);
        return Result.success();
    }

    @Operation(summary = "转成成亚马逊账号", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/transferAmazonAccount/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:email:transferAmazonAccount')")
    public Result<?> transferAmazonAccount(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        sysEmailService.transferAmazonAccount(ids);
        return Result.success();
    }

    @Operation(summary = "获取50条未注册的邮箱进行注册")
    @GetMapping("/getEmailMissions")
    public Result<?> getEmailMissions(HttpServletRequest request) {
        Result<?> result = RequestUtils.resolveAppToken(request, secret, appId);
        if (!Result.isSuccess(result)) {
            return result;
        }
        List<SysEmail> unRegisterEmailList = sysEmailService.getEmailMissions();
        return Result.success(unRegisterEmailList);
    }

    @Operation(summary = "更新状态")
    @PostMapping("/updateStatus")
    public Result<?> updateStatus(@RequestBody List<SysEmailForm> sysEmailFormList) {
        boolean result = sysEmailService.updateStatus(sysEmailFormList);
        for (SysEmailForm sysEmailForm : sysEmailFormList) {
            // 从任务队列删除
            AmazonContext.REGISTER_EMAIL_QUEUE.removeIf(item -> Objects.equals(item.getEmail(), sysEmailForm.getEmail()));
        }
        return Result.judge(result);
    }


    @Operation(summary = "邮箱表导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sysEmailImport")
    @PreAuthorize("@ss.hasPerm('sys:email:import')")
    @PreventDuplicateSubmit
    public Result<?> sysEmailImport(@RequestParam("file") MultipartFile file) throws Exception {
        SysEmailListener listener = new SysEmailListener();
        EasyExcelFactory.read(file.getInputStream(), SysEmailImportVo.class, listener).sheet(0).doRead();
        List<SysEmailImportVo> list = listener.getVos();
        if (list == null || list.size() == 0) {
            return Result.success();
        }
        // 删除数据为空的行
        list.removeIf(item -> !StringUtils.hasText(item.getEmail()));
        sysEmailService.importData(list);
        return Result.success();
    }

    @Operation(summary = "导出邮箱表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:email:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "邮箱表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SysEmailImportVo> sysEmailList = sysEmailService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), SysEmailImportVo.class).sheet("邮箱表").doWrite(sysEmailList);
    }
}

